package com.github.baichuan.gb32960.codec;

import com.github.baichuan.gb32960.utils.ByteBufHelper;
import com.github.baichuan.iot.protocol.pdu.Decoder;
import io.netty.buffer.ByteBuf;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 驱动电机数据
 */
public class DriveMotor implements Decoder {
    @Override
    public List<Map<String, Object>> decode(ByteBuf buf) {
        Map<String, Object> data = new TreeMap<>();

        // 驱动电机个数
        short quantity = buf.readUnsignedByte();
        data.put("quantity", quantity);

        // 驱动电机总成信息列表
        List<Map<String, Object>> motors = new ArrayList<>(quantity);
        data.put("motors", motors);
        for(int i = 0; i < quantity; i++){
            motors.add(Motor.INSTANCE.decode(buf).get(0));
        }

        return Arrays.asList(data);
    }

    /**
     * 驱动电机总成
     */
    public static class Motor implements Decoder {
        public final static Motor INSTANCE = new Motor();

        @Override
        public List<Map<String, Object>> decode(ByteBuf buf) {
            Map<String, Object> data = new TreeMap<>();

            // 电机序号
            data.put("no", buf.readUnsignedByte());

            // 电机状态
            data.put("mode", buf.readUnsignedByte());

            // 电机控制器温度
            ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
                data.put("cuTemp", value - 40);
            });

            // 电机转速
            ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
                data.put("rpm", value - 20000);
            });

            // 电机转矩
            ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
                data.put("torque", BigDecimal.valueOf(value * 0.1 - 2000).setScale(1, RoundingMode.HALF_UP));
            });

            // 电机温度
            ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
                data.put("temp", value - 40);
            });

            // 电机控制器输入电压
            ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
                data.put("cuInVoltage", BigDecimal.valueOf(value * 0.1).setScale(1, RoundingMode.HALF_UP));
            });

            // 电机控制器直流母线电压
            ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
                data.put("cuDcCurrent", BigDecimal.valueOf(value * 0.1 - 1000).setScale(1, RoundingMode.HALF_UP));
            });

            return Arrays.asList(data);
        }
    }
}
